import { defineStore } from 'pinia';

export type ProblemSeverity = 'error' | 'warning' | 'info';

export interface ProblemItem {
	id: string;
	severity: ProblemSeverity;
	message: string;
	file?: string;
	line?: number;
	column?: number;
}

export interface ProblemsState {
	items: ProblemItem[];
	severityFilter: Set<ProblemSeverity>;
	searchText: string;
	selectedId: string | null;
}

export const useProblemsStore = defineStore('problems', {
	state: (): ProblemsState => ({
		items: [],
		severityFilter: new Set(['error', 'warning', 'info']),
		searchText: '',
		selectedId: null,
	}),
	getters: {
		filteredItems: (state) => {
			return state.items.filter(item => {
				// Filter by severity
				if (!state.severityFilter.has(item.severity)) return false;
				// Filter by search text (message or file)
				if (state.searchText) {
					const query = state.searchText.toLowerCase();
					const message = (item.message || '').toLowerCase();
					const file = (item.file || '').toLowerCase();
					if (!message.includes(query) && !file.includes(query)) return false;
				}
				return true;
			});
		},
		selectedIndex(state) {
			const filtered = this.filteredItems as ProblemItem[];
			return state.selectedId ? filtered.findIndex((item) => item.id === state.selectedId) : -1;
		},
	},
	actions: {
		set(items: ProblemItem[]) { this.items = Array.isArray(items) ? items : []; },
		add(item: ProblemItem) { this.items.push(item); },
		clear() { this.items = []; },
		setSeverityFilter(severities: ProblemSeverity[]) {
			this.severityFilter = new Set(severities);
		},
		toggleSeverity(severity: ProblemSeverity) {
			const next = new Set(this.severityFilter);
			if (next.has(severity)) next.delete(severity);
			else next.add(severity);
			this.severityFilter = next;
		},
		setSearchText(text: string) {
			this.searchText = text || '';
		},
		setSelected(id: string | null) {
			this.selectedId = id;
		},
		navigateNext() {
			const filtered = this.filteredItems as ProblemItem[];
			if (!filtered.length) return null;
			const currentIndex = this.selectedIndex as number;
			const nextIndex = currentIndex >= 0 ? (currentIndex + 1) % filtered.length : 0;
			const nextItem = filtered[nextIndex];
			this.selectedId = nextItem.id;
			return nextItem;
		},
		navigatePrev() {
			const filtered = this.filteredItems as ProblemItem[];
			if (!filtered.length) return null;
			const currentIndex = this.selectedIndex as number;
			const prevIndex = currentIndex >= 0 ? (currentIndex - 1 + filtered.length) % filtered.length : filtered.length - 1;
			const prevItem = filtered[prevIndex];
			this.selectedId = prevItem.id;
			return prevItem;
		},
	},
});


